package edison.jcr;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jcr.Credentials;
import javax.jcr.LoginException;
import javax.jcr.NoSuchWorkspaceException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.Value;

import org.apache.commons.lang.ArrayUtils;

final class RepositoryImpl implements Repository {

	private final Map<String, Object> repositoryDescriptor = new HashMap<String, Object>();
	private static final String[] StandardDescriptor;

	static {
		List<String> temp = new ArrayList<String>();
		try {
			for (Field field : Repository.class.getDeclaredFields()) {
				temp.add(field.get(null).toString());
			}

		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		StandardDescriptor = temp.toArray(ArrayUtils.EMPTY_STRING_ARRAY);

	}

	public String[] getDescriptorKeys() {
		return repositoryDescriptor.keySet().toArray(new String[] {});
	}

	public boolean isStandardDescriptor(String key) {
		return ArrayUtils.contains(StandardDescriptor, key);
	}

	public boolean isSingleValueDescriptor(String key) {
		if (repositoryDescriptor.containsKey(key)) {
			Object value = repositoryDescriptor.get(key);
			return value instanceof Value;
		}

		return false;
	}

	public Value getDescriptorValue(String key) {
		if (isSingleValueDescriptor(key)) {
			return (Value) repositoryDescriptor.get(key);
		}

		return null;
	}

	public Value[] getDescriptorValues(String key) {
		if (!isSingleValueDescriptor(key)) {
			return (Value[]) repositoryDescriptor.get(key);
		}

		return null;
	}

	public String getDescriptor(String key) {
		return null;
	}

	public Session login(Credentials credentials, String workspaceName) throws LoginException, NoSuchWorkspaceException, RepositoryException {
		return new SessionImpl(this, workspaceName, new SimpleCredentials("admin", "admin".toCharArray()));
	}

	public Session login(Credentials credentials) throws LoginException, RepositoryException {
		return new SessionImpl(this, "workspaceName", new SimpleCredentials("admin", "admin".toCharArray()));
	}

	public Session login(String workspaceName) throws LoginException, NoSuchWorkspaceException, RepositoryException {
		return new SessionImpl(this, workspaceName, new SimpleCredentials("admin", "admin".toCharArray()));
	}

	public Session login() throws LoginException, RepositoryException {
		return new SessionImpl(this, "workspaceName", new SimpleCredentials("admin", "admin".toCharArray()));
	}
}